package co.fitstart.weapp.api.handler.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.demo2do.core.entity.exception.BusinessException;

import co.fitstart.weapp.api.handler.ImageHandler;

/**
 * 
 * @author haiyan_xiao
 *
 */
@Component("imageHandler")
public class ImageHandlerImpl implements ImageHandler {

    private static final Logger logger = LoggerFactory.getLogger(ImageHandlerImpl.class);
    
    @Value("#{config['file.upload.path']}")
    private String uploadPath;
    
    @Value("#{config['contrast_photo.path']}")
    private String contrastPhotoPath;

    /*
     * (non-Javadoc)
     * @see co.fitstart.weapp.api.handler.ImageHandler#upload(org.springframework.web.multipart.MultipartFile, java.lang.String)
     */
    public String upload(MultipartFile photo, String name) {
        try {
            InputStream inputStream = photo.getInputStream();
            
            // 1. 新建文件 （新建文件名为系统指定文件名，扩展名为源文件扩展名， 路径为指定路径）
            File file = new File(this.uploadPath + this.contrastPhotoPath, name + ".jpg");
            
            // 2. 将字节流copy到新文件
            try {
                FileUtils.copyInputStreamToFile(inputStream, file);
            } catch (IOException e) {
                logger.error("ImageHandlerImpl#save() error", e);
                throw new BusinessException("文件存储失败");
            }
            
            // 3. 返回文件路径 + 文件名 + 扩展名
            return this.contrastPhotoPath + "/" + name + ".jpg";
        } catch (IOException e) {
            logger.error("ImageHandlerImpl#upload() error", e);
            throw new BusinessException("文件存储失败");
        }
    }

}
